<script>
import { computed, defineComponent, onMounted, ref, toRaw } from 'vue'
import AFolder from '@Components/aFolder'
import AFile from '@Components/aFile'
import { fileType, getOneFileType } from '@Config/const'
import Sortable from 'sortablejs'
import { useStore } from 'vuex'
import { cloneDeep, findIndex } from 'lodash'
import * as Antd from 'ant-design-vue'
import { getDomAttributeByFolderId } from '@Untils'

/**

[{createTime: "2022-04-15 17:34:28"
fileMd5: ""
fileSize: 0
fileType: 0
fileUrl: ""
folderLevel: 1
id: 1
lastOperatorId: 0
lastOperatorName: ""
name: "新建文件夹"
operatorId: 0
operatorName: ""
pid: 0
updateTime: "2022-04-15 17:34:31"}]*/
export default defineComponent({
  props: {
    list: {
      type: Array,
      required: true,
    },
    role: {
      type: String,
      default: 'common',
    },
    rightMenuFn: {
      type: Function,
      default: () => {
        return []
      },
    },
  },
  emits: ['select', 'checkBox', 'reposDrop', 'attribute'],
  setup(props, context) {
    let role = computed(() => {
      return props.role
    })
    let list = computed(() => {
      return props.list
    })
    let rightMenuFn = computed(() => {
      return props.rightMenuFn
    })
    let folderSelectHandler = (e) => {
      context.emit('select', e)
    }

    let checkBoxHandler = (e) => {
      context.emit('checkBox', e)
    }

    let reposDropHandler = (e) => {
      context.emit('reposDrop', e)
    }

    let store = useStore()
    // onMounted(() => {
    //   setTimeout(() => {
    //     if (fref.value) {
    //       var sortable = Sortable.create(fref.value, {
    //         sort: false,
    //         onEnd: async (evt) => {
    //           console.log(evt)
    //         },
    //       })
    //     }
    //   }, 100)
    // })

    let attributeHandler = (e) => {
      context.emit('attribute', e)
    }

    let fn = (_obj) => {
      return (
        <Antd.Menu selectedKeys={[]}>
          {props.rightMenuFn(_obj)?.map((x) => {
            return (
              <Antd.MenuItem
                onClick={x.action.bind(null, { ...cloneDeep(_obj) })}
              >
                <Antd.Button size="small" type="link">
                  {x.label}
                </Antd.Button>
              </Antd.MenuItem>
            )
          })}
        </Antd.Menu>
      )
    }
    let fref = ref()

    let getDataById = (_id) => {
      let _index = findIndex(list.value, { id: parseInt(_id) })
      if (_index < 0) {
        console.error('发生错误了！')
      } else {
        return list.value[_index]
      }
    }
    /**
     * 根据事件，获取dom，从dom属性的data-folderid中获取当前元素
     */
    let contextMenuHandler = (e) => {
      let { dataId, dom } = getDomAttributeByFolderId(e)
      if (dataId != undefined) {
        let _obj = getDataById(dataId)
        e.rightMenu = fn(_obj)
        //dom.style.backgroundColor = '#ff00ff'
      }
    }

    let clickHandler = (e) => {
      let { dataId } = getDomAttributeByFolderId(e)
      if (dataId != undefined) {
        let _obj = getDataById(dataId)
        context.emit('checkBox', {
          target: { ...toRaw(_obj) },
          e: {
            target: {
              checked: !_obj.selected,
            },
          },
        })
      }
    }
    /**
     *
     * @description 双击监听
     */
    let dblclickHandler = (e) => {
      let { dataId } = getDomAttributeByFolderId(e)
      if (dataId) {
        let _obj = getDataById(dataId)
        //文件夹类型，回收站里面不允许双击，其它可以
        if (_obj.fileType == 0) {
          if (role.value == 'common') {
            context.emit('select', { target: toRaw(_obj) })
          }
        } else {
          store.commit('preivew', { visible: true, src: _obj.fileUrl })
        }
      }
    }
    return {
      list,
      folderSelectHandler,
      checkBoxHandler,
      role,
      fref,
      attributeHandler,
      reposDropHandler,
      rightMenuFn,
      store,
      fn,
      contextMenuHandler,
      clickHandler,
      dblclickHandler,
    }
  },
  render() {
    return (
      <>
        {this.list.length == 0 ? (
          <a-empty />
        ) : (
          <>
            <div
              class={{ fileList: true, [this.store.state.folderUi]: true }}
              ref="fref"
              onContextmenu={(e) => {
                this.contextMenuHandler(e)
              }}
              onClick={this.clickHandler}
              onDblclick={this.dblclickHandler}
            >
              {this.store.state.folderUi == 'list' && (
                <div>
                  <div class="file_content">
                    <div></div>
                    <div>名称</div>
                    <div>类型</div>
                    <div>创建时间</div>
                    <div>分享有效期</div>
                    <div>分享/被分享人</div>
                  </div>
                </div>
              )}
              {this.list.map((x) => {
                return (
                  <AFolder
                    key={x.id}
                    info={x}
                    onSelect={this.folderSelectHandler}
                    // onCheckBox={this.checkBoxHandler}
                    onReposDrop={this.reposDropHandler}
                    // onAttribute={this.attributeHandler}
                    rightMenuFn={this.rightMenuFn}
                    role={this.role}
                  />
                )
                //let _r = getOneFileType((xx) => xx.value == x.fileType)
                // if (_r.value == 0) {
                //   return (
                //     <AFolder
                //       info={x}
                //       onSelect={this.folderSelectHandler}
                //       onMoveTrash={this.moveTrashHandler}
                //       onRemove={this.removeHandler}
                //       onCheckBox={this.checkBoxHandler}
                //       onRecovery={this.recoveryHandler}
                //       role={this.role}
                //     />
                //   )
                // } else {
                //   return (
                //     <AFile
                //       info={x}
                //       onMoveTrash={this.moveTrashHandler}
                //       onRemove={this.removeHandler}
                //       onCheckBox={this.checkBoxHandler}
                //       onRecovery={this.recoveryHandler}
                //       role={this.role}
                //     />
                //   )
                // }
              })}
            </div>
          </>
        )}
      </>
    )
  },
})
</script>
